import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
import { Notice } from 'iview'
/**
 * axios配置,请求前端拦截,构建Promise调用请求
 */

let alertMsg = (nodesc = "请求出现异常", title = "服务端提示") => {
    debugger
    Notice.error({
        title: title,
        desc: nodesc,
        duration: 0
    });
}

let loadding = () => {
    //加载中
}
let closeLoadding = () => {
    //取消加载中
}

/**
 * 格式化请求地址
 */
let parseUrl = url => {
    if (url.indexOf("_dc=") < 0) {
        if (url.indexOf("?") >= 0) {
            url = url + "&_dc=" + (new Date().getTime());
        } else {
            url = url + "?_dc=" + (new Date().getTime());
        }
    }
    return url;
};

/**
 * 判断服务端是否出错
 */
let isServerError = json => {
    if (!json) {
        return true;
    }
    var data = json;
    if (typeof json == 'string' && json.indexOf('{"ClassId":"_SERVER_ERROR_",') >= 0) {
        //if (typeof json == 'string') {// 服务端返回字符串,也转成对象,要求服务端返回都必须是json格式,不能是简单的数值或字符串
        data = JSON.parse(json);
    }
    if (data.ClassId && data.HasError) {
        alertMsg(data.Message);
        return true;
    }
    return false;
};

//axios配置
axios.defaults.timeout = 5000; //com.defalutAxios.timeOut
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; // com.defalutAxios.postContentType
axios.defaults.baseURL = 'http:///192.168.0.51:10001/'; ///com.defalutAxios.baseURL
//POST传参序列化
axios.interceptors.request.use((config) => {
    loadding(); //加载中
    config.url = parseUrl(config.url);
    if (config.method === 'post') {
        config.data = qs.stringify(config.data);
    }
    return config;
}, (error) => {
    debugger
    closeLoadding()
    alertMsg(error);
    return Promise.reject(error);
});

//返回状态判断
axios.interceptors.response.use((res) => {
    closeLoadding();
    if (isServerError(res.data)) {
        return Promise.reject(res.data);
    }
    return res;
}, (error) => {
    closeLoadding();
    let msg = `
        URL:${error.config.url}\n
        Error:${error.message}\n
        Status:${error.request.status}\n
        ReadyState:${error.request.readyState}\n
        TextStatus:${error.statusText}\n
    `;
    alertMsg(msg);
    return Promise.reject(error);
});


//构建Promise异步回调函数
export default {
    queryData: (url, params) => {
        return new Promise((resolve, reject) => {
            axios.get(url, { params })
                .then(response => {
                    resolve(response.data);
                })
                .catch((error) => {
                    reject(error)
                })
        });
    },
    postData: (url, params) => {
        return new Promise((resolve, reject) => {
            axios.post(url, params)
                .then(response => {
                    resolve(response.data);
                })
                .catch((error) => {
                    reject(error)
                })
        });
    }

}